package service

import (
	"net/http"
	"url_shorten/common/response"
	"url_shorten/common/validate"
	"url_shorten/internal/def"
	"url_shorten/internal/dto"
	"url_shorten/internal/model"

	"github.com/gin-gonic/gin"
)

var statsChan = make(chan string, 100)

func init() {
	go computeShortenStats()
}

func computeShortenStats() {
	for {
		code := <-statsChan
		model.IncrStatsByShortenCode(code)
	}
}

// @Summary 短链生成
// @Description 短链生成
// @Tags 短链
// @Accept json
// @Produce json
// @Param data body dto.ShortenDTO true "短链生成"
// @Success 200 {object} dto.ShortenUrlResponse "短链生成"
// @Router /api/shorten [post]
func ShortenUrlGet(c *gin.Context) {
	var req dto.ShortenDTO
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Fail(c, validate.Translate(err))
	    return
	}
	code, err := model.GetShortenUrl(req.Url)
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	response.SuccessStruct(c, dto.ShortenUrlResponse{ShortenUrl: def.HttpProtocol + c.Request.Host + "/" + code})
}

// @Summary 短链统计
// @Description 短链统计
// @Tags 短链
// @Accept json
// @Produce json
// @Success 200 {object} []dto.ShortenStatisticsItem "短链统计"
// @Router /api/statistics [get]
func ShortenStatistics(c *gin.Context)  {
	stats,  err:= model.GetStats()
	if err!= nil {
		response.Fail(c, err.Error())
		return	
	}
	response.SuccessStruct(c, stats)
}

// @Summary 短链统计
// @Description 短链统计
// @Tags 短链
// @Accept json
// @Produce json
// @Param shorten_code path string true "短链"
// @Success 200 {object} dto.ShortenStatisticsItem "短链统计"
// @Router /api/statistics/{shorten_code} [get]
func ShortenStatisticsByCode(c *gin.Context)  {
    	code := c.Param("shorten_code")
		num,  err:= model.GetStatsByShortenCode(code)
		if err!= nil {
			response.Fail(c, err.Error())
			return
		}
		response.SuccessStruct(c, dto.ShortenStatisticsItem{ShortenUrl: code, Statistics: num})
}


// @Summary 短链跳转
// @Description 短链跳转
// @Tags 短链
// @Accept json
// @Produce json
// @Param shorten_code path string true "短链"
// @Success 302 {object} string "短链跳转"
// @Router /{shorten_code} [get]
func ShortenRedirect(c *gin.Context)  {
	code := c.Param("shorten_code")
	url, err := model.GetOriginUrl(code)
	if err!= nil {
		response.Fail(c, err.Error())
		return
	}
	statsChan <- code
	c.Redirect(http.StatusFound, url)
}
